package com.blog.controller.admin;

import com.blog.properties.QiniuOssProperties;
import com.blog.result.Result;
import com.blog.utils.QiniuOssUtil;
import com.blog.utils.StrUtil;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
    @RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private QiniuOssUtil qiniuOssUtil;
    @Autowired
    private QiniuOssProperties qiniuOssProperties;
    private final String QiniuUploadFilePath = "vlog_img/";

    /**
     * 上传到七牛云的OOS对象存储服务器
     */
    @PostMapping("/upload")
    public Result<Map<String, String>> upload(@RequestParam("file") MultipartFile file) {
        log.info("上传的文件：{}", file);

        try {
            int size = (int) file.getSize() + 1024 * 2;
            byte[] FileBytes = new byte[size];
            FileBytes = file.getBytes();

            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String onlyFileId = QiniuUploadFilePath + StrUtil.getOnlyFileId(originalFilename);

            //文件的请求路径
            //构造一个带指定Zone对象的配置类（具体是指对应的哪一个区，就是指新建存储空间的时候用的是哪一个区）
            Configuration cfg = new Configuration(Zone.huanan());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //获取唯一上传的认证
            String upToken = qiniuOssUtil.createQiniuUpToken(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey(), qiniuOssProperties.getBucketName());
            //上传文件到七牛云
            Response response = uploadManager.put(FileBytes, onlyFileId, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(
                    response.bodyString(), DefaultPutRet.class);
            Map<String, String> data = new HashMap<>();
            data.put("url", qiniuOssProperties.getDomainName() + putRet.key);
            return Result.success(data, "上传成功....");
        } catch (Exception e) {
            log.error("文件上传失败.....{}", e);
        }
        return Result.fail("文件上传失败");
    }

}
